package cn.kjcoder.redis.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author hkj
 * @email 1349091387@qq.com
 * @date 2022/1/21
 * 源码允许修改，并且本人十分乐意有 大佬 来对代码进行 随 意 调 教
 **/
@RestController
@Slf4j@RequestMapping("/thumb")
public class ThumbsController {

    @Autowired
    private RedisTemplate redisTemplate;
    public static final String LIKE_KEY = "like:";

    /**
     * 点赞
     */
    @GetMapping("/dolike")
    public String dolike(int postId,int userId){
        String result = "";
        try {
            String key = LIKE_KEY + postId;
            Long val = this.redisTemplate.opsForSet().add(key, userId);
            if(val == 1){
                result = "点赞成功";
            }else{
                result = "重复点赞";
            }
            log.info("查询结果：{}", val);
        } catch (Exception e) {
            log.error("exception:", e);
        }
        return result;
    }

    /**
     * 取消点赞
     */
    @GetMapping("/dislike")
    public String dislike(int postId,int userId){
        String result = "";
        try {
            String key = LIKE_KEY + postId;
            Long val = this.redisTemplate.opsForSet().remove(key, userId);
            if(val == 1){
                result = "取消点赞成功";
            }else{
                result = "重复取消点赞";
            }
            log.info("查询结果：{}", val);
        } catch (Exception e) {
            log.error("exception:", e);
        }
        return result;
    }

    /**
     * 根据postid userid查看帖子信息，返回结果是点赞总数和是否点赞
     */
    @GetMapping("/getpost")
    public Map getPost(int postId,int userId){
        Map map = new HashMap();
        try {
            String key = LIKE_KEY + postId;
            Long size = this.redisTemplate.opsForSet().size(key);
            Boolean exist = this.redisTemplate.opsForSet().isMember(key, userId);
            map.put("size",size);
            map.put("exist",exist);
            log.info("查询结果：{}", map);
        } catch (Exception e) {
            log.error("exception:", e);
        }
        return map;
    }

    /**
     * 查看点赞明细，就是有哪些人
     */
    @GetMapping("/likedetail")
    public Set likedetail(int postId){
        Set members = null;
        try {
            String key = LIKE_KEY + postId;
            members = this.redisTemplate.opsForSet().members(key);
            log.info("查询结果：{}", members);
        } catch (Exception e) {
            log.error("exception:", e);
        }
        return members;
    }
}
